package com.fernfx.xingtan.common.webview;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.fernfx.xingtan.R;
import com.fernfx.xingtan.common.base.BaseActivity;

import butterknife.BindView;

/**
 * Created by admin on 2018/8/21.
 * 公共的webview做一些加载静态页面的操作
 */

public class WebViewActivity extends BaseActivity {
    public static final String WEBVIEW_URL = "webview_url";
    public static final String TITLE_TEXT = "title_key";

    @BindView(R.id.common_wviw)
    WebView webView;
    @BindView(R.id.load_probar)
    ProgressBar loadProbar;

    public static void start(Context context, String url, String title) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(WEBVIEW_URL, url);
        intent.putExtra(TITLE_TEXT, title);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_common_web_view;
    }

    @Override
    protected void initView() {
        //set title
        Intent intent = getIntent();
        String titleText = intent.getStringExtra(TITLE_TEXT);
        setToolbarTitle(titleText);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        WebSettings seting = webView.getSettings();
        seting.setJavaScriptEnabled(true);//设置webview支持javascript脚本
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if (newProgress == 100) {
                    loadProbar.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    loadProbar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    loadProbar.setProgress(newProgress);//设置进度值
                }
            }
        });
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        //url
        String url = intent.getStringExtra(WEBVIEW_URL);
        webView.loadUrl(url);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO 自动生成的方法存根
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {//当webview不是处于第一页面时，返回上一个页面
                webView.goBack();
                return true;
            } else {//当webview处于第一页面时,直接退出程序
                System.exit(0);
            }


        }
        return super.onKeyDown(keyCode, event);
    }


}
